
import {getSmsCode, getAuthCode, login, currentUser, queryTenantList, binding} from '@/services/login';
import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
  CalculatorOutlined
} from '@ant-design/icons';
import { createFromIconfontCN } from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
  ProFormSelect, ProFormInstance
} from '@ant-design/pro-form';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import {Alert, Spin, message, Tabs} from 'antd';
import Settings from '../../../config/defaultSettings';
import React, {useState, useRef, useEffect} from 'react';
import {useBoolean, useRequest} from 'ahooks';
import Footer from "@/components/Footer";
import {useNavigate} from "react-router-dom";
import {useStore} from "jotai";
import initialStatesAtom from "@/store/initialStatesAtom";
import VerifySlideFixed from '@/components/AjCaptcha/verifySlideFixed';
import defaultSettings from "../../../config/defaultSettings.tsx";
import {API} from "@/services/typings";

const IconFont = createFromIconfontCN({
  scriptUrl: defaultSettings.iconfontUrl, // 在 iconfont.cn 上生成
});
const ActionIcons = () => {
  const [messageApi] = message.useMessage();

  const langClassName = useEmotionCss(({ token }) => {
    return {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    };
  });

  return (
    <>
      <IconFont onClick={()=>{
        messageApi.open({
          type: 'loading',
          content: '认证中...',
          duration: 0,
        });
        binding('gitee').then((response)=>{
          messageApi.destroy()
          if(response.data.code ===200){
            window.location.href = response.data.data
          }else{
            messageApi.open({
              type: 'error',
              content: response.data.msg,
              duration: 3,
            })
          }
        })
      }} key="gitee" type="icon-mayun" className={langClassName}/>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={langClassName} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={langClassName} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={langClassName} />
    </>
  );
};

let promiseResolve: any = () => {}
let promiseReject: any = () => {}

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const navigate = useNavigate();
  const store = useStore();
  useEffect(() => {
    store.set(initialStatesAtom, {currentUser: {
            roles: [],
            permissions: []
        },isAuthenticated:false});
  }, [1]);
  const formRef = useRef<ProFormInstance>();
  const [userLoginState, setUserLoginState] = useState({code:200,msg:''});
  const [type, setType] = useState<string>('password');
  const [state, { setTrue, setFalse }] = useBoolean(false);

  const { data:tenant } = useRequest(queryTenantList,
      {
        onFinally: (params, data, e) => {
          console.log('queryTenantList onFinally', data,params,e)
        }
      });

  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    };
  });
  /**
   * 根据配置切换验证码类型
   */
  const { data: authCode, loading: codeLoading,run: reflushAuthCode } = useRequest(async () => {
    const res = await getAuthCode();
    if (res) {
      console.log('authCode', res.data)
      return res.data.data;
    }
    return {};
  },{
    ready: import.meta.env.VITE_CAPTCHA_TYPE !== 'slider',
  });


  const fetchUserInfo = async () => {
    const userInfo = await currentUser();
    console.log('---fetchUserInfo--',userInfo)
    store.set(initialStatesAtom,{currentUser:userInfo.data.data,isAuthenticated:true})
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const {data,status} = await login({ ...values, grantType:type,clientId:import.meta.env.VITE_CLIENT_ID,uuid:authCode?.uuid });
      if (status === 200 && data.code === 200) {
        localStorage.setItem('token', data.data.access_token);
        await fetchUserInfo()
        navigate('/', { replace: true });
        message.success("登录成功");
        return;
      }
      console.log(data.data);
      // 如果失败去设置用户错误信息
      setUserLoginState(data);
      message.error(data.msg);
      reflushAuthCode()
    } catch (error) {
      console.log(error)
      message.error('登录失败，请重试！');
    }
  };
  const handleVerifyResult = async (result: any) => {
    console.log('---handleVerifyResult---',result)
    setFalse()
    if(result){
      const values = formRef.current?.getFieldsValue()
      await handleSubmit({...values,ajCaptchaData:JSON.stringify(result)})
    }
    promiseResolve()
  }
  /**
   * 发送短信验证码
   * @param result
   */
  const handleSmsSendVerifyResult = async (result: any) => {
    console.log('---handleSmsSendVerifyResult---',result)
    setFalse()
    if(result){
      const {phonenumber,tenantId} = formRef.current?.getFieldsValue()
      const smsResult = await getSmsCode({
        phonenumber,
        tenantId,
        ajCaptchaData:JSON.stringify(result)
      });
      if (!smsResult) {
        promiseReject()
        return
      }
      message.success('获取验证码成功！验证码为：1234');
      promiseResolve()
    }else{
      promiseReject()
    }
  }
  const { code,msg} = userLoginState;

  return (
    <div className={containerClassName}>
      <VerifySlideFixed isShow={state} verifyPointFixedChild={type==='password'?handleVerifyResult:handleSmsSendVerifyResult} />
      <title>
        登录页- {Settings.title}
      </title>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          formRef={formRef}
          logo={<img alt="logo" src={Settings.logo} />}
          title="Quick-Admin"
          subTitle="快速开发后台管理系统"
          initialValues={{
            autoLogin: true,
          }}
          actions={[
            <>其他登录方式</>,
            <ActionIcons key="icons" />,
          ]}
          onFinish={async (values) => {
            if(type === 'password') {
              return new Promise(async (resolve, reject) => {
                promiseResolve = resolve;
                promiseReject = reject;
                setTrue()
              })
            }else {
              await handleSubmit(values);
            }
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'password',
                label: '账户密码登录',
              },
              {
                key: 'sms',
                label: '手机号登录',
              },
            ]}
          />

          {code !== 200 && type === 'password' && (
            <LoginMessage
              content={msg}
            />
          )}
          {code !== 200 && type === 'sms' && <LoginMessage content={msg} />}
          {tenant?.data?.data.tenantEnabled&&<ProFormSelect
            name="tenantId"
            fieldProps={{
              size: 'large'
            }}
            request={async (params) =>{
              console.log('---request---',params)
              if (tenant && tenant?.data?.data.tenantEnabled) {
                // @ts-ignore
                return tenant?.data?.data.voList.map((item) => {
                  return {
                    label: item.companyName,
                    value: item.tenantId,
                  }
                })
              }
              return []
            }}
            placeholder="请选择公司"
            rules={[{ required: true, message: '请选择公司!' }]}
          />}
          {type === 'password' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'用户名'}
                rules={[
                  {
                    required: true,
                    message: "请输入用户名!",
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              {import.meta.env.VITE_CAPTCHA_TYPE !== 'slider'&&<ProFormText
                name="code"
                placeholder="请输入验证码"
                fieldProps={{
                  size: 'large',
                  prefix: <CalculatorOutlined />,
                  suffix: <Spin spinning={codeLoading}>
                    <img onClick={reflushAuthCode} style={{height:'25px',cursor:'pointer'}} src={`data:image/gif;base64,${authCode?.img}`} alt="验证码"/>
                  </Spin>
                }}
              />}
            </>
          )}
          {type === 'sms' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined />,
                }}
                name="phonenumber"
                placeholder="手机号"
                rules={[
                  {
                    required: true,
                    message: "请输入手机号！",
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: "手机号格式错误！",
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder="请输入验证码"
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} 获取验证码`;
                  }
                  return '获取验证码';
                }}
                phoneName="phonenumber"
                name="smsCode"
                rules={[
                  {
                    required: true,
                    message: '请输入验证码！',
                  },
                ]}
                onGetCaptcha={ () => new Promise(async (resolve, reject) => {
                  promiseReject= reject;
                  promiseResolve = resolve;
                  const {tenantId} = formRef.current?.getFieldsFormatValue?.()
                  if(tenant?.data.data.tenantEnabled&&!tenantId) {
                    message.error('请输入先选择所属企业！');
                    promiseReject()
                    return
                  }
                  setTrue()
                  })
                }
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              忘记密码
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
